package app

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
)

const configFlagName = "config"

var configFile string

func init() {
	pflag.StringVarP(&configFile, configFlagName, "c", configFile, "Read configuration from specified `FILE`,"+
		"support JSON, TOML, YAML, HCL or java properties formats.")
}

// addConfigFlag 添加一个用于指定配置文件的flag
func addConfigFlag(basename string, fs *pflag.FlagSet) {
	fs.AddFlag(pflag.Lookup(configFlagName))

	viper.AutomaticEnv()
	viper.SetEnvPrefix(strings.Replace(strings.ToUpper(basename), "-", "_", -1))
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
	cobra.OnInitialize(func() {
		if len(configFile) != 0 {
			viper.SetConfigFile(configFile)
		} else {
			homeDir, err := os.UserHomeDir()
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error: failed to get user home dir. %v\n", err)
				os.Exit(1)
			}

			viper.AddConfigPath(filepath.Join(homeDir, "."+basename))
			viper.SetConfigName(basename)
		}

		if err := viper.ReadInConfig(); err != nil {
			fmt.Fprintf(os.Stderr, "Error: failed to read configuration file(%s): %v\n", configFile, err)
		}
	})
}
